<?php
declare (strict_types = 1);
namespace app\api\controller;

use think\Request;
use think\Exception;
use think\facade\{Db, Log};
use think\exception\ValidateException;

use app\api\controller\BaseController;
use service\JsonService as Json;

use app\common\model\{User, Shop, ShopCate, Goods, Order, OrderCart, GoodsCart, UserAddress};
use app\common\validate\{UserValidate, ShopValidate};

class OrderController extends BaseController
{
    /**
	 * 加入购物车
	 */
    public function addCart()
    {
        $goodsId = Request()->param('goods_id', 0);
        $price   = Request()->param('price', 0);
        $number  = Request()->param('number', 0);
        $sku     = Request()->param('sku', []);

        if($goodsId === 0 || $price === 0 || $number === 0) return Json::fail('数据错误!');
        if(GoodsCart::getFind(['user_id' => $this->user_id, 'goods_id' => $goodsId]) !== false) return Json::fail('商品已存在');

        $info = Goods::getFind(['id' => $goodsId]);

        if($info === false) return Json::fail('商品不存在');

        $data = [
            'user_id'  => $this->user_id,
            'shop_id'  => $info['shop_id'],
            'goods_id' => $goodsId,
            'price'    => $price,
            'number'   => $number,
            'sku'      => $sku,
        ];

        $flag = GoodsCart::add($data);
        if($flag === false) return Json::fail('加入购物车失败！');
        return Json::success('加入成功');
    }

    /**
	 * 购物车列表
	 */
    public function getCartList()
    {
        $page  = Request()->param('page', 1);
        $limit = Request()->param('limit', 10);

        $list = GoodsCart::getCartList($this->user_id, $page, $limit);

        if($list === false) return Json::fail('暂无数据！');
        return Json::success('ok', $list);
    }

    /**
	 * 移出购物车
	 */
    public function delCartGoods()
    {
        $goodsId  = Request()->param('goods_id', 1);
        $list = GoodsCart::del(['user_id' => $this->user_id, 'goods_id' => $goodsId]);
        if($list === false) return Json::fail('删除失败！');
        return Json::success('删除成功');
    }

    /**
	 * 购物车商品修改数量
	 */
    public function setCartNumber()
    {
        $goodsId = Request()->param('goods_id', 1);
        $number  = Request()->param('number', 1);
        $flag = GoodsCart::editWhere(['number' => $number], ['user_id' => $this->user_id, 'goods_id' => $goodsId]);
        if($flag === false) return Json::fail('修改失败！');
        return Json::success('修改成功');
    }

    /**
	 * 确认订单
	 */
    public function orderConfirm()
    {
        $goodsIds  = Request()->param('goods_ids', '');
        $goodsIds  = json_decode($goodsIds);

        /** 用户的默认地址 */
        $addressInfo = UserAddress::getFind(['user_id' => $this->user_id, 'is_default' => 1], 'id, name, mobile, address');
        $list = GoodsCart::orderConfirm($this->user_id, $goodsIds);

        if($list === false) return Json::fail('暂无数据！');
        return Json::success('ok', ['address_info' => $addressInfo, 'shop_list' => $list]);
    }

    /**
	 * 提交订单
	 */
    public function addOrder()
    {
        // $data = [
        //     [
        //         "shop_id"          => 1,  /** 店铺ID */
        //         "shop_name"        => 'XX店铺',  /** 店铺名称 */
        //         "price"            => 1000.00,  /** 该店铺消费的金额 */
        //         "is_brokerage"     => 0,  /** 佣金抵扣（1=是，0=否），需要前端自己拼进去 */
        //         "user_brokerage"   => 0.00,  /** 用户佣金余额 */
        //         "rebate_brokerage" => 10,  /** 抵扣佣金（不抵扣的话为返利佣金） */
        //         "is_money_red"     => 0,  /** 红包抵扣（1=是，0=否），需要前端自己拼进去 */
        //         "goods_list"       => [
        //             [
        //                 "id"               => 8,
        //                 "name"             => '商品',
        //                 "small_img"        => 'http://leishan.shop.com/storage/goods/20210924/58f710a127bb01d27c224f746e780ed4.png',
        //                 "type"             => '佣金商品',
        //                 "price"            => 1000.00,
        //                 "number"           => 1,
        //                 "sku"              => [],
        //                 "rebate_brokerage" => 10,
        //             ]
        //         ]
        //     ]
        // ];

        // return json_encode($data);

        $addressId    = Request()->param('address_id', 0);
        $price        = Request()->param('price', 0);
        $payType      = Request()->param('pay_type', 0);
        $shopListJson = Request()->param('shop_list', '');
        $payType      = Request()->param('pay_type', 0);
        $shopList     = json_decode($shopListJson, true);

        if($addressId == 0) return Json::fail('请选择收货地址！');

        $addressInfo = UserAddress::getFind(['id' => $addressId]);
        if($addressInfo === false) return Json::fail('收货地址不存在！');
        
        /** 购物车订单号 */
        $orderNoCart = getOrderNo();

        $orderCartData = [
            'order_no'   => $orderNoCart,
            'user_id'    => $this->user_id,
            'price'      => $price,
            'shop_list'  => $shopListJson,
        ];

        $orderData = [];

        Db::startTrans();
        try {
            $OrderCartFlag = OrderCart::add($orderCartData);
            if($OrderCartFlag === false) throw new Exception('生成购物车订单失败！');

            foreach($shopList as $shopArr){
                $orderData[] = [
                    'order_no'         => getOrderNo(),
                    'user_id'          => $this->user_id,
                    'shop_id'          => $shopArr['shop_id'],
                    'order_cart_id'    => $OrderCartFlag->id,
                    'price'            => $shopArr['price'],
                    'goods_list'       => json_encode($shopArr['goods_list']),
                    'receiver_name'    => $addressInfo['name'],
                    'receiver_mobile'  => $addressInfo['mobile'],
                    'receiver_address' => $addressInfo['address'],
                    'pay_type'         => $payType,
                    'status'           => 0,
                    'is_brokerage'     => $shopArr['is_brokerage'],
                    'is_money_red'     => $shopArr['is_money_red'],
                    'brokerage'        => isset($shopArr['rebate_brokerage']) ? $shopArr['rebate_brokerage'] : 0,
                    'money_red'        => isset($shopArr['rebate_money_red']) ? $shopArr['rebate_money_red'] : 0,
                    'point'            => isset($shopArr['rebate_point']) ? $shopArr['rebate_point'] : 0,
                ];
            }

            $orderFlag = Order::addAll($orderData);
            if($orderFlag === false) throw new Exception('生成订单失败！');

            $payData['openid']    = User::getVal(['id' => $this->user_id], 'openid');
            $payData['order_no']  = $orderNoCart;
            $payData['total_fee'] = $price;
            $payData['body']      = '购物车结算';
            $payData['notify']    = 'notify';

            $payController = new WxpayController();
            $payBackData   = $payController->pay($payData);

            if($payBackData['code'] == 400) throw new Exception($payBackData['return_msg']);

            Db::commit();    
        }catch(Exception $e){
            Db::rollback();
            return Json::fail($e->getMessage());
        }

        return Json::success('ok', $payBackData['sign']);
    }

    /**
	 * 确认订单（单个商品）
	 */
    public function orderConfirmOnce()
    {
        $goodsId = Request()->param('goods_id', 0);
        $price   = Request()->param('price', 0);
        $number  = Request()->param('number', 1);
        $sku     = Request()->param('sku', '');

        /** 用户的默认地址 */
        $addressInfo = UserAddress::getFind(['user_id' => $this->user_id, 'is_default' => 1], 'id, name, mobile, address');
        $info = Goods::orderConfirm($this->user_id, $goodsId, $price, $number, $sku);

        if($info === false) return Json::fail('暂无数据！');
        return Json::success('ok', ['address_info' => $addressInfo, 'shop_info' => $info]);
    }

    /**
	 * 提交订单（单个商品）
	 */
    public function orderAddOnce()
    {
        $addressId       = Request()->param('address_id', 0);
        $price           = Request()->param('price', 0);
        $shopId          = Request()->param('shop_id', 0);
        $isBrokerage     = Request()->param('is_brokerage', 0);
        $rebateBrokerage = Request()->param('rebate_brokerage', 0);
        $isMoneyRed      = Request()->param('is_money_red', 0);
        $rebateMoneyRed  = Request()->param('rebate_money_red', 0);
        $point           = Request()->param('point', 0);
        $payType         = Request()->param('pay_type', 0);
        $goodsListJson   = Request()->param('goods_list', '');
        $goodsList       = json_decode($goodsListJson, true);

        if($addressId == 0) return Json::fail('请选择收货地址！');

        $addressInfo = UserAddress::getFind(['id' => $addressId]);
        if($addressInfo === false) return Json::fail('收货地址不存在！');
        
        /** 订单号 */
        $orderNo = getOrderNo();

        Db::startTrans();
        try {
            $orderData = [
                'order_no'         => $orderNo,
                'user_id'          => $this->user_id,
                'shop_id'          => $shopId,
                'order_cart_id'    => 0,
                'price'            => $price,
                'goods_list'       => json_encode($goodsList),
                'receiver_name'    => $addressInfo['name'],
                'receiver_mobile'  => $addressInfo['mobile'],
                'receiver_address' => $addressInfo['address'],
                'pay_type'         => $payType,
                'status'           => 0,
                'is_brokerage'     => $isBrokerage,
                'is_money_red'     => $isMoneyRed,
                'brokerage'        => $rebateBrokerage,
                'money_red'        => $rebateMoneyRed,
                'point'            => $point,
            ];

            $orderFlag = Order::add($orderData);
            if($orderFlag === false) throw new Exception('生成订单失败！');

            $payData['openid']    = User::getVal(['id' => $this->user_id], 'openid');
            $payData['order_no']  = $orderNo;
            $payData['total_fee'] = $price;
            $payData['body']      = $goodsList[0]['name'];
            $payData['notify']    = 'notify';

            $payController = new WxpayController();
            $payBackData   = $payController->pay($payData);

            if($payBackData['code'] == 400) throw new Exception($payBackData['return_msg']);

            Db::commit();    
        }catch(Exception $e){
            Db::rollback();
            return Json::fail($e->getMessage());
        }

        return Json::success('ok', $payBackData['sign']);
    }

    /**
     * 订单支付
     */
    public function orderPay()
    {
        $orderId = Request()->param('order_id', 0);
        $payData = Order::orderPay($this->user_id, $orderId);

        if(!isset($payData['appId'])) return Json::fail('支付信息错误');
        return Json::success('ok', $payData);
    }
}